<template>
  <div class="personal-info">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="info-card">
          <div class="title">个人信息</div>
          <div class="avatar-container">
            <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
            >
              <img v-if="avatarUrl" :src="avatarUrl" class="avatar"/>
              <el-icon v-else class="avatar-uploader-icon">
                <Plus/>
              </el-icon>
            </el-upload>
          </div>
          <div class="info-list">
            <div class="info-item">
              <span class="label">用户昵称：</span>
              <span class="value">{{ userStore.user.name }}</span>
            </div>
            <div class="info-item">
              <span class="label">当前角色：</span>
              <span class="value">{{ userStore.role == null ? '暂无角色' : userStore.role.roleName }}</span>
            </div>
            <div class="info-item">
              <span class="label">当前权限：</span>
              <el-tooltip :content="permissionVal" placement="top">
                <span class="value">{{ permissionVal }}</span>
              </el-tooltip>
            </div>
            <div class="info-item">
              <span class="label">所有角色：</span>
              <el-tooltip :content="roles" placement="top">
                <span class="value">{{ roles }}</span>
              </el-tooltip>
            </div>
            <div class="info-item">
              <span class="label">登录地址：</span>
              <span class="value">{{ userStore.user.loginIp }}</span>
            </div>
            <div class="info-item">
              <span class="label">登录时间：</span>
              <span class="value">{{ formatTimestamp(userStore.user.loginDate) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card class="info-card">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本资料" name="info">
              <el-form
                  ref="formRef"
                  :model="form"
                  :rules="rules"
                  label-width="100px"
                  class="personal-form"
              >
                <el-form-item style="width: 500px" label="用户昵称" prop="name">
                  <el-input disabled v-model="form.username"/>
                </el-form-item>
                <el-form-item style="width: 500px" label="用户昵称" prop="name">
                  <el-input v-model="form.name"/>
                </el-form-item>
                <el-form-item style="width: 500px" label="邮箱" prop="email">
                  <el-input v-model="form.email"/>
                </el-form-item>
                <el-form-item style="width: 500px" label="电话" prop="phone">
                  <el-input v-model="form.phone"/>
                </el-form-item>
                <el-form-item style="margin-top: 30px">
                  <el-button type="primary" @click="submitForm(formRef)">保存</el-button>
                  <el-button style="margin-left: 30px" type="danger" @click="$router.push({path: '/'})">关闭</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="修改密码" name="password">
              <el-form
                  ref="pwdFormRef"
                  :model="resetPWDParams"
                  :rules="pwdRules"
                  label-width="100px"
                  class="personal-form"
              >
                <el-form-item style="width: 500px" label="旧密码" prop="oldPassword">
                  <el-input type="password" v-model="resetPWDParams.oldPassword" show-password/>
                </el-form-item>
                <el-form-item style="width: 500px" label="新密码" prop="password">
                  <el-input type="password" v-model="resetPWDParams.password" show-password/>
                </el-form-item>
                <el-form-item style="width: 500px" label="确认密码" prop="password2">
                  <el-input type="password" v-model="resetPWDParams.password2" show-password/>
                </el-form-item>
                <el-form-item style="margin-top: 30px">
                  <el-button type="primary" @click="submitPwdForm(pwdFormRef)">保存</el-button>
                  <el-button style="margin-left: 30px" type="danger" @click="$router.push({path: '/'})">关闭</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="js">
import {ref, reactive, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import {reqAddOrUpdateUser, reqResetPassword} from '@/api/system/user'
import useUserStore from '@/store/modules/user'
import {useRouter} from "vue-router";
import setting from "@/setting.js";
import {formatTimestamp} from "@/utils/time.js";

let $router = useRouter();
const userStore = useUserStore()
const avatarUrl = ref()
const formRef = ref()
const pwdFormRef = ref()
const activeTab = ref('info')
const permissionVal = ref('')
const roles = ref('')
const form = reactive({})

//重置密码
let resetPWDParams = reactive({
  //用户id
  userId: 0,
  //原始密码
  oldPassword: '',
  //新密码
  password: '',
  //是否校验原始密码
  verify: '',
  //重置密码二次确认
  password2: '',
});

const rules = reactive({
  name: [
    {required: true, message: '请输入姓名', trigger: 'blur'},
    {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        const chineseAndEnglishAndNumberRegex = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/;
        if (!chineseAndEnglishAndNumberRegex.test(value)) {
          callback(new Error('姓名只能包含中文、英文和数字'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  email: [
    {required: true, message: '请输入邮箱地址', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入电话号码', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'}
  ]
})

const pwdRules = reactive({
  oldPassword: [
    {required: true, message: '请输入旧密码', trigger: 'blur'},
    {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}
  ],
  password2: [
    {required: true, message: '请确认密码', trigger: 'blur'},
    {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== resetPWDParams.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

const handleAvatarSuccess = (response) => {
  avatarUrl.value = URL.createObjectURL(response.raw)
}

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      reqAddOrUpdateUser(form).then(() => {
        ElMessage.success('个人信息更新成功')
        //获取用户信息
        userStore.userInfo()
      }).catch(() => {
        ElMessage.error('个人信息更新失败')
      })
    } else {
      ElMessage.error('请填写完整信息')
      return false
    }
  })
}

const submitPwdForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      resetPWDParams.userId = userStore.user.id;
      resetPWDParams.verify = true;
      //重置密码
      let result = reqResetPassword(resetPWDParams);
      if (result.code == setting.SYSTEM_SUCCESS) {
        ElMessage({type: 'success', message: '密码修改成功'});
      }
      resetPWDParams.oldPassword = ''
      resetPWDParams.password = ''
      resetPWDParams.password2 = ''
      activeTab.value = 'password'
    } else {
      ElMessage.error('请填写完整信息')
      return false
    }
  })
}

onMounted(async () => {
  // 获取用户信息
  await userStore.userInfo();

  const {id, name, email, phone, status, avatar, username} = userStore.user;
  Object.assign(form, {id, name, email, phone, status, avatar, username});

  // 设置头像 URL
  avatarUrl.value =  setting.avatar;
  //avatarUrl.value = avatar || setting.avatar;

  // 获取所有权限
  permissionVal.value = userStore.permissions
      .filter(({permissionVal}) => permissionVal)
      .map(({menuName}) => menuName)
      .join('、');

  // 获取所有角色
  roles.value = userStore.roles.map(({roleName}) => roleName).join('、');
});


</script>

<style scoped lang="scss">
.personal-info {
  .info-card {
    height: 100%;

    .title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 1px solid var(--el-border-color-light);
    }
  }

  .avatar-container {
    text-align: center;
    padding: 20px;
  }

  .avatar-uploader {
    :deep(.el-upload) {
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
    line-height: 120px;
  }

  .avatar {
    width: 120px;
    height: 120px;
    display: block;
    border-radius: 50%;
  }

  .info-list {
    padding: 20px 40px;

    .info-item {
      margin-bottom: 15px;
      line-height: 24px;
      display: flex;
      align-items: center;
      width: 100%;
      border-bottom: 1px solid var(--el-border-color-light);

      .label {
        color: var(--el-text-color-secondary);
        flex-shrink: 0;
      }

      .value {
        margin-left: 40px;
        color: var(--el-text-color-primary);
        flex: 1;
        min-width: 0;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        position: relative;
      }
    }
  }


  .personal-form {
    padding: 20px;
  }
}
</style>
